package com.demo.mangyThread.threadException.csdn;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * @Author: lkz
 * @Title: CatchThreadPoolException
 * @Description: 线程池
 * @Date: 2023/3/28 11:44
 */
@Slf4j
public class CatchThreadPoolException {

    public static void main(String[] args) {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                2,
                4,
                1L,
                TimeUnit.MINUTES,
                new LinkedBlockingDeque<>(1024),
                new ThreadFactory() {
                    @Override
                    public Thread newThread(Runnable r) {
                        Thread thread = new Thread(r);
                        //设置线程异常处理器
                        thread.setUncaughtExceptionHandler(new CustomThreadUncaughtExceptionHandler());
                        return thread;
                    }
                }
        );

        threadPoolExecutor.execute(new Runnable() {
                                       @Override
                                       public void run() {
                                           throw new RuntimeException("execute()发生异常");
                                       }
                                   }
        );

        threadPoolExecutor.submit(new Runnable() {
            @Override
            public void run() {
                throw new RuntimeException("submit.run()发生异常");
            }
        });

        threadPoolExecutor.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                throw new RuntimeException("submit.call()发生异常");
            }
        });
        threadPoolExecutor.shutdown();
    }

    /**
     * 结果: 并不符合预期，预期应该捕获三个异常
     * 只捕获到了通过execute()提交的任务的异常
     * 没有捕获到通过submit()提交的任务的异常
     * 通过afterExecute()捕获submit()任务的异常
     * 通过submit()方法的源码可以发现，submit()是将runnable()封装成了RunnableFuture<Void>，并最终调用execute(ftask);执行。
     *
     */

}
